"use strict";

var _interopRequireWildcard = require("@babel/runtime/helpers/interopRequireWildcard").default;

var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault").default;

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.getFormatMessage = exports.default = void 0;

var _slicedToArray2 = _interopRequireDefault(require("@babel/runtime/helpers/slicedToArray"));

var _objectSpread2 = _interopRequireDefault(require("@babel/runtime/helpers/objectSpread2"));

var _regeneratorRuntime2 = _interopRequireDefault(require("@babel/runtime/helpers/regeneratorRuntime"));

var _asyncToGenerator2 = _interopRequireDefault(require("@babel/runtime/helpers/asyncToGenerator"));

var _jsxRuntime = require("react/jsx-runtime");

var _icons = require("@ant-design/icons");

var _proUtils = require("@ant-design/pro-utils");

var _ssrDarkreader = require("@umijs/ssr-darkreader");

var _useParams = require("@umijs/use-params");

var _antdV = require("antd-v4");

var _omit = _interopRequireDefault(require("omit.js"));

var _useMergedState5 = _interopRequireDefault(require("rc-util/lib/hooks/useMergedState"));

var _react = require("react");

var _defaultSettings = _interopRequireDefault(require("../../defaultSettings"));

var _locales = require("../../locales");

var _utils = require("../../utils/utils");

var _BlockCheckbox = _interopRequireDefault(require("./BlockCheckbox"));

require("./index.less");

var _LayoutChange = _interopRequireWildcard(require("./LayoutChange"));

var _RegionalChange = _interopRequireDefault(require("./RegionalChange"));

var _ThemeColor = _interopRequireDefault(require("./ThemeColor"));

var Body = function Body(_ref) {
  var children = _ref.children,
      prefixCls = _ref.prefixCls,
      title = _ref.title;
  return (0, _jsxRuntime.jsxs)("div", {
    style: {
      marginBottom: 24
    },
    children: [(0, _jsxRuntime.jsx)("h3", {
      className: "".concat(prefixCls, "-drawer-title"),
      children: title
    }), children]
  });
};

var getDifferentSetting = function getDifferentSetting(state) {
  var stateObj = {};
  Object.keys(state).forEach(function (key) {
    if (state[key] !== _defaultSettings.default[key] && key !== 'collapse') {
      stateObj[key] = state[key];
    } else {
      stateObj[key] = undefined;
    }

    if (key.includes('Render')) stateObj[key] = state[key] === false ? false : undefined;
  });
  stateObj.menu = undefined;
  return stateObj;
};

var getFormatMessage = function getFormatMessage() {
  var formatMessage = function formatMessage(_ref2) {
    var id = _ref2.id;
    var locales = (0, _locales.gLocaleObject)();
    return locales[id];
  };

  return formatMessage;
};

exports.getFormatMessage = getFormatMessage;

var updateTheme = /*#__PURE__*/function () {
  var _ref3 = (0, _asyncToGenerator2.default)( /*#__PURE__*/(0, _regeneratorRuntime2.default)().mark(function _callee(dark, color) {
    var defaultTheme, defaultFixes;
    return (0, _regeneratorRuntime2.default)().wrap(function _callee$(_context) {
      while (1) {
        switch (_context.prev = _context.next) {
          case 0:
            if (!(typeof window === 'undefined')) {
              _context.next = 2;
              break;
            }

            return _context.abrupt("return");

          case 2:
            if (!(typeof window.MutationObserver === 'undefined')) {
              _context.next = 4;
              break;
            }

            return _context.abrupt("return");

          case 4:
            if (_antdV.ConfigProvider.config) {
              _context.next = 6;
              break;
            }

            return _context.abrupt("return");

          case 6:
            _antdV.ConfigProvider.config({
              theme: {
                primaryColor: (0, _utils.genStringToTheme)(color) || '#1890ff'
              }
            });

            if (dark) {
              defaultTheme = {
                brightness: 100,
                contrast: 90,
                sepia: 10
              };
              defaultFixes = {
                invert: [],
                css: '',
                ignoreInlineStyle: ['.react-switch-handle'],
                ignoreImageAnalysis: [],
                disableStyleSheetsProxy: true
              };

              if (window.MutationObserver && window.fetch) {
                (0, _ssrDarkreader.setFetchMethod)(window.fetch);
                (0, _ssrDarkreader.enable)(defaultTheme, defaultFixes);
              }
            } else {
              if (window.MutationObserver) (0, _ssrDarkreader.disable)();
            }

          case 8:
          case "end":
            return _context.stop();
        }
      }
    }, _callee);
  }));

  return function updateTheme(_x, _x2) {
    return _ref3.apply(this, arguments);
  };
}();
/**
 * 初始化的时候需要做的工作
 *
 * @param param0
 */


var initState = function initState(urlParams, settings, onSettingChange) {
  if (!(0, _proUtils.isBrowser)()) return;
  var replaceSetting = {};
  Object.keys(urlParams).forEach(function (key) {
    if (_defaultSettings.default[key] || _defaultSettings.default[key] === undefined) {
      if (key === 'primaryColor') {
        replaceSetting[key] = (0, _utils.genStringToTheme)(urlParams[key]);
        return;
      }

      replaceSetting[key] = urlParams[key];
    }
  });
  var newSettings = (0, _proUtils.merge)({}, settings, replaceSetting);
  delete newSettings.menu;
  delete newSettings.title;
  delete newSettings.iconfontUrl; // 同步数据到外部

  onSettingChange === null || onSettingChange === void 0 ? void 0 : onSettingChange(newSettings); // 如果 url 中设置主题，进行一次加载。

  if (_defaultSettings.default.navTheme !== urlParams.navTheme && urlParams.navTheme) {
    updateTheme(settings.navTheme === 'realDark', urlParams.primaryColor);
  }
};

var getParamsFromUrl = function getParamsFromUrl(urlParams, settings) {
  if (!(0, _proUtils.isBrowser)()) return _defaultSettings.default;
  return (0, _objectSpread2.default)((0, _objectSpread2.default)((0, _objectSpread2.default)({}, _defaultSettings.default), settings || {}), urlParams);
};

var genCopySettingJson = function genCopySettingJson(settingState) {
  return JSON.stringify((0, _omit.default)((0, _objectSpread2.default)((0, _objectSpread2.default)({}, settingState), {}, {
    primaryColor: settingState.primaryColor
  }), ['colorWeak']), null, 2);
};
/**
 * 可视化配置组件
 *
 * @param props
 */


var SettingDrawer = function SettingDrawer(props) {
  var _props$defaultSetting = props.defaultSettings,
      propsDefaultSettings = _props$defaultSetting === void 0 ? undefined : _props$defaultSetting,
      _props$settings = props.settings,
      propsSettings = _props$settings === void 0 ? undefined : _props$settings,
      hideHintAlert = props.hideHintAlert,
      hideCopyButton = props.hideCopyButton,
      _props$colorList = props.colorList,
      colorList = _props$colorList === void 0 ? [{
    key: 'daybreak',
    color: '#1890ff'
  }, {
    key: 'dust',
    color: '#F5222D'
  }, {
    key: 'volcano',
    color: '#FA541C'
  }, {
    key: 'sunset',
    color: '#FAAD14'
  }, {
    key: 'cyan',
    color: '#13C2C2'
  }, {
    key: 'green',
    color: '#52C41A'
  }, {
    key: 'geekblue',
    color: '#2F54EB'
  }, {
    key: 'purple',
    color: '#722ED1'
  }] : _props$colorList,
      getContainer = props.getContainer,
      onSettingChange = props.onSettingChange,
      enableDarkTheme = props.enableDarkTheme,
      _props$prefixCls = props.prefixCls,
      prefixCls = _props$prefixCls === void 0 ? 'ant-pro' : _props$prefixCls,
      _props$pathname = props.pathname,
      pathname = _props$pathname === void 0 ? window.location.pathname : _props$pathname,
      _props$disableUrlPara = props.disableUrlParams,
      disableUrlParams = _props$disableUrlPara === void 0 ? true : _props$disableUrlPara,
      themeOnly = props.themeOnly;
  var firstRender = (0, _react.useRef)(true);

  var _useMergedState = (0, _useMergedState5.default)(false, {
    value: props.collapse,
    onChange: props.onCollapseChange
  }),
      _useMergedState2 = (0, _slicedToArray2.default)(_useMergedState, 2),
      show = _useMergedState2[0],
      setShow = _useMergedState2[1];

  var _useState = (0, _react.useState)((0, _locales.getLanguage)()),
      _useState2 = (0, _slicedToArray2.default)(_useState, 2),
      language = _useState2[0],
      setLanguage = _useState2[1];

  var _useUrlSearchParams = (0, _useParams.useUrlSearchParams)({}, {
    disabled: disableUrlParams
  }),
      _useUrlSearchParams2 = (0, _slicedToArray2.default)(_useUrlSearchParams, 2),
      urlParams = _useUrlSearchParams2[0],
      setUrlParams = _useUrlSearchParams2[1];

  var _useMergedState3 = (0, _useMergedState5.default)(function () {
    return getParamsFromUrl(urlParams, propsSettings || propsDefaultSettings);
  }, {
    value: propsSettings,
    onChange: onSettingChange
  }),
      _useMergedState4 = (0, _slicedToArray2.default)(_useMergedState3, 2),
      settingState = _useMergedState4[0],
      setSettingState = _useMergedState4[1];

  var _ref4 = settingState || {},
      navTheme = _ref4.navTheme,
      primaryColor = _ref4.primaryColor,
      layout = _ref4.layout,
      colorWeak = _ref4.colorWeak;

  (0, _react.useEffect)(function () {
    // 语言修改，这个是和 locale 是配置起来的
    var onLanguageChange = function onLanguageChange() {
      if (language !== (0, _locales.getLanguage)()) {
        setLanguage((0, _locales.getLanguage)());
      }
    };
    /** 如果不是浏览器 都没有必要做了 */


    if (!(0, _proUtils.isBrowser)()) return function () {
      return null;
    };
    initState(getParamsFromUrl(urlParams, propsSettings), settingState, setSettingState);
    window.document.addEventListener('languagechange', onLanguageChange, {
      passive: true
    });
    return function () {
      return window.document.removeEventListener('languagechange', onLanguageChange);
    }; // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []);
  (0, _react.useEffect)(function () {
    updateTheme(settingState.navTheme === 'realDark', settingState.primaryColor);
  }, [settingState.primaryColor, settingState.navTheme]);
  /**
   * 修改设置
   *
   * @param key
   * @param value
   */

  var changeSetting = function changeSetting(key, value) {
    var nextState = {};
    nextState[key] = value;

    if (key === 'layout') {
      nextState.contentWidth = value === 'top' ? 'Fixed' : 'Fluid';
    }

    if (key === 'layout' && value !== 'mix') {
      nextState.splitMenus = false;
    }

    if (key === 'layout' && value === 'mix') {
      nextState.navTheme = 'light';
    }

    if (key === 'colorWeak' && value === true) {
      var dom = document.querySelector('body');

      if (dom) {
        dom.dataset.prosettingdrawer = dom.style.filter;
        dom.style.filter = 'invert(80%)';
      }
    }

    if (key === 'colorWeak' && value === false) {
      var _dom = document.querySelector('body');

      if (_dom) {
        _dom.style.filter = _dom.dataset.prosettingdrawer || 'none';
        delete _dom.dataset.prosettingdrawer;
      }
    }

    delete nextState.menu;
    delete nextState.title;
    delete nextState.iconfontUrl;
    delete nextState.logo;
    delete nextState.pwa;
    setSettingState((0, _objectSpread2.default)((0, _objectSpread2.default)({}, settingState), nextState));
  };

  var formatMessage = getFormatMessage();
  (0, _react.useEffect)(function () {
    /** 如果不是浏览器 都没有必要做了 */
    if (!(0, _proUtils.isBrowser)()) return;
    if (disableUrlParams) return;

    if (firstRender.current) {
      firstRender.current = false;
      return;
    }
    /** 每次从url拿最新的防止记忆 */


    var urlSearchParams = new URLSearchParams(window.location.search);
    var params = Object.fromEntries(urlSearchParams.entries());
    var diffParams = getDifferentSetting((0, _objectSpread2.default)((0, _objectSpread2.default)({}, params), settingState));
    delete diffParams.logo;
    delete diffParams.menu;
    delete diffParams.title;
    delete diffParams.iconfontUrl;
    delete diffParams.pwa;
    setUrlParams(diffParams);
  }, [setUrlParams, settingState, urlParams, pathname, disableUrlParams]);
  var baseClassName = "".concat(prefixCls, "-setting");
  return (0, _jsxRuntime.jsx)(_antdV.Drawer, {
    visible: show,
    width: 300,
    closable: false,
    onClose: function onClose() {
      return setShow(false);
    },
    placement: "right",
    getContainer: getContainer,
    handler: (0, _jsxRuntime.jsx)("div", {
      className: "".concat(baseClassName, "-drawer-handle"),
      onClick: function onClick() {
        return setShow(!show);
      },
      children: show ? (0, _jsxRuntime.jsx)(_icons.CloseOutlined, {
        style: {
          color: '#fff',
          fontSize: 20
        }
      }) : (0, _jsxRuntime.jsx)(_icons.SettingOutlined, {
        style: {
          color: '#fff',
          fontSize: 20
        }
      })
    }),
    style: {
      zIndex: 999
    },
    children: (0, _jsxRuntime.jsxs)("div", {
      className: "".concat(baseClassName, "-drawer-content"),
      children: [(0, _jsxRuntime.jsx)(Body, {
        title: formatMessage({
          id: 'app.setting.pagestyle',
          defaultMessage: 'Page style setting'
        }),
        prefixCls: baseClassName,
        children: (0, _jsxRuntime.jsx)(_BlockCheckbox.default, {
          prefixCls: baseClassName,
          list: [{
            key: 'light',
            title: formatMessage({
              id: 'app.setting.pagestyle.light',
              defaultMessage: '亮色菜单风格'
            })
          }, {
            key: 'dark',
            title: formatMessage({
              id: 'app.setting.pagestyle.dark',
              defaultMessage: '暗色菜单风格'
            })
          }, {
            key: 'realDark',
            title: formatMessage({
              id: 'app.setting.pagestyle.realdark',
              defaultMessage: '暗色菜单风格'
            })
          }].filter(function (item) {
            if (item.key === 'dark' && settingState.layout === 'mix') return false;
            if (item.key === 'realDark' && !enableDarkTheme) return false;
            return true;
          }),
          value: navTheme,
          configType: "theme",
          onChange: function onChange(value) {
            return changeSetting('navTheme', value);
          }
        }, "navTheme")
      }), colorList !== false && (0, _jsxRuntime.jsx)(Body, {
        title: formatMessage({
          id: 'app.setting.themecolor',
          defaultMessage: 'Theme color'
        }),
        prefixCls: baseClassName,
        children: (0, _jsxRuntime.jsx)(_ThemeColor.default, {
          colorList: colorList,
          value: (0, _utils.genStringToTheme)(primaryColor),
          formatMessage: formatMessage,
          onChange: function onChange(color) {
            return changeSetting('primaryColor', color);
          }
        })
      }), !themeOnly && (0, _jsxRuntime.jsxs)(_jsxRuntime.Fragment, {
        children: [(0, _jsxRuntime.jsx)(_antdV.Divider, {}), (0, _jsxRuntime.jsx)(Body, {
          prefixCls: baseClassName,
          title: formatMessage({
            id: 'app.setting.navigationmode'
          }),
          children: (0, _jsxRuntime.jsx)(_BlockCheckbox.default, {
            prefixCls: baseClassName,
            value: layout,
            configType: "layout",
            list: [{
              key: 'side',
              title: formatMessage({
                id: 'app.setting.sidemenu'
              })
            }, {
              key: 'top',
              title: formatMessage({
                id: 'app.setting.topmenu'
              })
            }, {
              key: 'mix',
              title: formatMessage({
                id: 'app.setting.mixmenu'
              })
            }],
            onChange: function onChange(value) {
              return changeSetting('layout', value);
            }
          }, "layout")
        }), (0, _jsxRuntime.jsx)(_LayoutChange.default, {
          settings: settingState,
          changeSetting: changeSetting
        }), (0, _jsxRuntime.jsx)(_antdV.Divider, {}), (0, _jsxRuntime.jsx)(Body, {
          prefixCls: baseClassName,
          title: formatMessage({
            id: 'app.setting.regionalsettings'
          }),
          children: (0, _jsxRuntime.jsx)(_RegionalChange.default, {
            settings: settingState,
            changeSetting: changeSetting
          })
        }), (0, _jsxRuntime.jsx)(_antdV.Divider, {}), (0, _jsxRuntime.jsx)(Body, {
          prefixCls: baseClassName,
          title: formatMessage({
            id: 'app.setting.othersettings'
          }),
          children: (0, _jsxRuntime.jsx)(_antdV.List, {
            split: false,
            renderItem: _LayoutChange.renderLayoutSettingItem,
            dataSource: [{
              title: formatMessage({
                id: 'app.setting.weakmode'
              }),
              action: (0, _jsxRuntime.jsx)(_antdV.Switch, {
                size: "small",
                className: "color-weak",
                checked: !!colorWeak,
                onChange: function onChange(checked) {
                  changeSetting('colorWeak', checked);
                }
              })
            }]
          })
        }), hideHintAlert && hideCopyButton ? null : (0, _jsxRuntime.jsx)(_antdV.Divider, {}), hideHintAlert ? null : (0, _jsxRuntime.jsx)(_antdV.Alert, {
          type: "warning",
          message: formatMessage({
            id: 'app.setting.production.hint'
          }),
          icon: (0, _jsxRuntime.jsx)(_icons.NotificationOutlined, {}),
          showIcon: true,
          style: {
            marginBottom: 16
          }
        }), hideCopyButton ? null : (0, _jsxRuntime.jsx)(_antdV.Button, {
          block: true,
          icon: (0, _jsxRuntime.jsx)(_icons.CopyOutlined, {}),
          style: {
            marginBottom: 24
          },
          onClick: function () {
            var _onClick = (0, _asyncToGenerator2.default)( /*#__PURE__*/(0, _regeneratorRuntime2.default)().mark(function _callee2() {
              return (0, _regeneratorRuntime2.default)().wrap(function _callee2$(_context2) {
                while (1) {
                  switch (_context2.prev = _context2.next) {
                    case 0:
                      _context2.prev = 0;
                      _context2.next = 3;
                      return navigator.clipboard.writeText(genCopySettingJson(settingState));

                    case 3:
                      _antdV.message.success(formatMessage({
                        id: 'app.setting.copyinfo'
                      }));

                      _context2.next = 8;
                      break;

                    case 6:
                      _context2.prev = 6;
                      _context2.t0 = _context2["catch"](0);

                    case 8:
                    case "end":
                      return _context2.stop();
                  }
                }
              }, _callee2, null, [[0, 6]]);
            }));

            function onClick() {
              return _onClick.apply(this, arguments);
            }

            return onClick;
          }(),
          children: formatMessage({
            id: 'app.setting.copy'
          })
        })]
      })]
    })
  });
};

var _default = SettingDrawer;
exports.default = _default;